package com.SpringbootVue.interceptors;

import com.SpringbootVue.utils.JwtUtil;
import com.SpringbootVue.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        String token = request.getHeader("Authorization");        //获取浏览器中的，令牌验证
        try {        //验证token
            //从redis中获取相同的token
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redisToken = operations.get(token);
            if (redisToken==null){
                //token已经失效了
                throw new RuntimeException();
            }
            Map<String, Object> claims = JwtUtil.parseToken(token);//当验证不过时抛出异常，否则正常执行
            //把业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(claims);
            System.out.println("登录验证拦截，通过");
            return true;  //放行
        } catch (Exception e) {//当验证不过时抛出异常
            //http响应状态码为401
            response.setStatus(401);
            System.out.println("登录验证拦截，不通过，未登录");
            return false; //不放行
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}
